package com.jiaai.cloud.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jiaai.cloud.base.entity.RestResultGenerator;
import com.jiaai.cloud.base.exception.ServiceException;
import com.jiaai.cloud.base.page.CustomPage;
import com.jiaai.cloud.base.page.FrontPage;
import com.jiaai.cloud.base.redis.util.RedisUtil;
import com.jiaai.cloud.base.weixin.util.WeiXinUtil;
import com.jiaai.cloud.wx.entity.TEmp;
import com.jiaai.cloud.wx.entity.TPay;
import com.jiaai.cloud.wx.schedular.PayScheduledTasks;
import com.jiaai.cloud.wx.service.ITEmpService;
import com.jiaai.cloud.wx.service.ITPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 佳爱网络科技
 * @since 2017-08-28
 */
@Controller
@RequestMapping("/api/v1/temp")
public class TEmpController {
    @Autowired
    private ITPayService itPayService;
    @Autowired
    private ITEmpService itEmpService;
    @Autowired
    private RedisUtil redisUtil;

    //todo
    /**
     * 员工自行领取日结工资
     * @param tPay
     * @return
     */
    @RequestMapping(value = "/getsalary",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"} )
    @ResponseBody
    public Object getSalary(@RequestBody TPay tPay){
        tPay.setStatus(1);
        try {
            itPayService.updateById(tPay);
            PayScheduledTasks.PAY_LIST.add(tPay);
            return RestResultGenerator.genSuccessResult("领取成功");
        } catch (Exception e){
            return new ServiceException("领取失败", e.getMessage());
        }
    }



    //todo tested
    /**
     * 查询员工自己的所有工资信息
     * @param empid
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/querymypaid",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"} )
    @ResponseBody
    public Object queryMyPay(@RequestHeader String empid, FrontPage frontPage)  throws ServiceException {
        Page<TPay> list = itPayService.selectPage(frontPage.getPagePlus(), new EntityWrapper<TPay>()
                .eq("empid", empid)
                .orderBy("status",false)
                .orderBy("createdate", false));
        try {
            return RestResultGenerator.genSuccessResult(new CustomPage<TPay>(list));
        }catch (Exception e) {
            throw new ServiceException("查询失败", e.getMessage());
        }
    }

    //todo
    /**
     * 员工输入邀请码后, 先访问的请求, 以得到微信的userInfo
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/toreg",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"} )
    @ResponseBody
    public Object toReg(String inviteCode, String code, @RequestBody TEmp tEmp)  throws ServiceException {
        String ic = redisUtil.getString(1, inviteCode);

        try {
            if ( ic == null || "".equals(ic) || inviteCode == null || ic.equalsIgnoreCase(inviteCode)){
                throw new Exception("邀请码错误或不存在");
            }
            Object session = WeiXinUtil.getAppSessionKey("wx2d74b3b5e1dc25ed", "6fa67444bcbc9c557ef9082d95c1a5db", code).get("session");
            JSONObject jsonObject = (JSONObject) session;
            String openid = jsonObject.get("openid").toString();

            tEmp.setGroupid(Integer.parseInt(ic.substring(6)));
            tEmp.setOpenID(openid);
            tEmp.setEmpid(ic);

            redisUtil.delKey(1, ic);

            return RestResultGenerator.genSuccessResult(tEmp);
        }catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("访问失败", e.getMessage());
        }
    }

    //todo
    /**
     * 注册员工
     * @param tEmp
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/reg",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"} )
    @ResponseBody
    public Object reg(@RequestBody TEmp tEmp) throws ServiceException {
        try {
            tEmp.setStatus(1);
            itEmpService.insert(tEmp);
            return RestResultGenerator.genSuccessResult("注册成功");
        }catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("注册失败", e.getMessage());
        }
    }

    //todo tested
    /**
     * 逻辑删除单个员工
     * @param empid
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/deleteone/{empid}",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"} )
    @ResponseBody
    public Object deleteOne(@PathVariable("empid") String empid) throws ServiceException {
        try {
            itEmpService.deleteLogically(empid);
            return RestResultGenerator.genSuccessResult("删除成功");
        } catch (Exception e){
            throw new ServiceException("删除失败", e.getMessage());
        }
    }



    //todo
    /**
     * 验证邮箱是否被注册了
     * @param email
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/valiemail",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"} )
    @ResponseBody
    public Object valiEmail(String email)  throws ServiceException {
        try {
            if (itEmpService.selectObj(new EntityWrapper<TEmp>().isNotNull("groupid").eq("email", email)) == null){
                return RestResultGenerator.genSuccessResult("邮箱未被注册");
            }
            throw new Exception("邮箱已被注册");
        }catch (Exception e) {
            throw new ServiceException("邮箱已被注册", e.getMessage());
        }
    }
}
